Cloudflare Workers
$ npx create-cloudflare my-app --framework hono \ --deploy false
$ cd my-app && npm run dev
.dev.vars
本地使用的環境變數
$ echo "ENV = \"local\"" >> .dev.vars
wrangler.toml
deploy 後使用的環境變數
code:wrangler.toml
name = "my-app"
compatibility_date = "2023-01-01"
ENV = "development"
index.ts
code:index.ts
import { Hono } from "hono";
const app = new Hono<{
Bindings: {
ENV: string;
};
}>();
app.get("/", (c) => c.text(c.env.ENV));
export default app;
使用wrangler指令加入middleware
需於wrangler.toml加上設定
KV
Key-Value store
npx wrangler kv:namespace create TEST_KV
copy ID and paste to wrangler.toml
code:wrangler.toml
kv_namespaces
binding = "TEST_KV"
id = "ID_HERE"
code:index.ts
// 名稱和 binding 相同
const app = new Hono<{
Bindings: { TEST_KV: KVNamespace }
}>();
app.get("/counter", async (c) => {
const key = c.req.query()"key" || "defaultKey"; const count = Number(await c.env.TEST_KV.get(key));
const count = !isNaN(value) ? value + 1 : 1;
// 存入 KV
await c.env.TEST_KV.put(key, String(count));
return c.text(String(count));
});
export default app;
kv.get(key)取值、kv.put(key, value)存值
Layout
code:src/renderer.tsx
import { jsxRenderer } from 'hono/jsx-renderer'
export const renderer = jsxRenderer(({ children }) => {
return (
<html>
<head>
</head>
<body>
<header>
<h1><a href="/">Title</a></h1>
</header>
<div>{children}</div>
</body>
</html>
)
})
code:src/index.tsx
app.get('/', (c) => {
return c.render(
<div>
<h2>Subtitle</h2>
<form action="/create" method="post">
<input type="text" name="url" autocomplete="off" style={{ width: '80%' }} />
<button type="submit">Submit</button>
</form>
</div>
)
})
LogPush
C3
Create Cloudflare CLI
D1
SQL Datebase
R2
Storage